import time
import smtplib
from core.myconfig import config
from email.header import Header
from email.mime.text import MIMEText

"""
用来发送邮件
"""

class Sender():
    def __init__(self, host="smtp.qq.com", subject=config['mailheader']):
        self.host = host
        self.user = config['sendemail']
        self.password = config['sendemailpasswd']
        self.msgsuccess = '<h2 >{}</h2>:{}'.format(config['mailsuccess'], config['mailcontent'])
        self.msgerror = '<h2 >{}</h2>:{}'.format(config['mailerror'], config['mailcontent'])
        self.subject = subject

    def send(self, email, success=True):
        """
        发送邮件
        """

        if success:
            message = MIMEText(self.msgsuccess, 'html', 'utf-8')
        else:
            message = MIMEText(self.msgerror, 'html', 'utf-8')

        message['From'] = Header("平安小助手工作组", 'utf-8')
        message['To'] = Header("尊敬的平安小助手用户", 'utf-8')
        message['Subject'] = Header(self.subject, 'utf-8')

        try:
            smtplibo = smtplib.SMTP_SSL(host=self.host, port=465)
            smtplibo.login(user=self.user, password=self.password)
            smtplibo.sendmail(self.user, email, message.as_string())
            print(email + "邮件发送成功:success")
            smtplibo.quit()
            return True
        except:
            print(email + "邮件发送失败:error")
            smtplibo.quit()
            return False

    def getemail(self, emails, success=True):
        """
        尝试发送两次 邮件。如果两次都失败，则将邮箱送入 error_email
        """
        again_email = []
        error_email = []
        for email in emails:
            # 垃圾代码
            # time.sleep(10)
            if self.send(email, success):
                pass
            else:
                again_email.append(email)

        for email in again_email:
            # 垃圾代码
            # time.sleep(10)
            if self.send(email, success):
                pass
            else:
                error_email.append(email)

        return error_email


if __name__ == '__main__':
    emails = ['2842936326@qq.com']
    sendemail = Sender()

    # 此处只能测试出 def send(self, email, success=True) 中 success=True 的情况
    erroremail = sendemail.getemail(emails)
    print(erroremail)
